package com.dinadi.yidi.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.FragmentTabHost;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.MessageBean;
import com.dinadi.yidi.bean.UpdateAppBean;
import com.dinadi.yidi.bean.UpdateAppRequest;
import com.dinadi.yidi.bean.UserInfoBean;
import com.dinadi.yidi.bean.UserInformationBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.MyApplication;
import com.dinadi.yidi.ui.fragment.Designer2Fragment;
import com.dinadi.yidi.ui.fragment.PersonalFragment;
import com.dinadi.yidi.ui.fragment.ShopWindowFragment;
import com.dinadi.yidi.ui.fragment.SpecialFragment;
import com.dinadi.yidi.ui.fragment.WatchingFragment;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UpdateManager;
import com.dinadi.yidi.utils.UtilPopupWindow;
import com.dinadi.yidi.utils.app.AppManager;

import de.greenrobot.event.EventBus;


/**
 * 首页
 */

public class MainActivity extends BaseActivity {
    private View view;
    private UtilPopupWindow popupWindow;
    private FragmentTabHost tabhost = null;
    private View indicator = null;
    private boolean loginState;
    private UpdateManager mUpdateManager;
    private UpdateAppRequest requestBean;
    private String userId, token;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        tabhost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

        // 添加tab名称和图标
       /* indicator = getIndicatorView("专题", R.layout.tabview1);
        tabhost.addTab(tabhost.newTabSpec("SpecialFragment")
                .setIndicator(indicator), SpecialFragment.class, null);*/
        indicator = getIndicatorView("美学堂", R.layout.tabview5);
        tabhost.addTab(tabhost.newTabSpec("WatchingFragment")
                .setIndicator(indicator), WatchingFragment.class, null);


        indicator = getIndicatorView("名师汇", R.layout.tabview2);
        tabhost.addTab(tabhost.newTabSpec("Designer2Fragment")
                .setIndicator(indicator), Designer2Fragment.class, null);

        indicator = getIndicatorView("艺精选", R.layout.tabview3);
        tabhost.addTab(tabhost.newTabSpec("ShopWindowFragment")
                .setIndicator(indicator), ShopWindowFragment.class, null);

        indicator = getIndicatorView("个人", R.layout.tabview4);
        tabhost.addTab(tabhost.newTabSpec("PersonalFragment")
                .setIndicator(indicator), PersonalFragment.class, null);
        //注册EventBus  接收页面
        EventBus.getDefault().register(this);
    }


    private View getIndicatorView(String name, int layoutId) {
        View v = getLayoutInflater().inflate(layoutId, null);
        TextView tv = (TextView) v.findViewById(R.id.tabText);
        tv.setText(name);
        return v;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tabhost = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initListener() {

    }

    @Override
    public void onResume() {
        super.onResume();
        loginState = SharePreferencesHelper.getInstance(MainActivity.this).getBoolean("loginState");
        userId = SharePreferencesHelper.getInstance(MainActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(MainActivity.this).getString("token");

    }

    @Override
    protected void initData() {
        /*判断有没有登录*/
        userId = SharePreferencesHelper.getInstance(MainActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(MainActivity.this).getString("token");
        UserInformationBean bean = new UserInformationBean();
        bean.setToken(token);
        bean.setUserId(userId);
        CommonInterface userInformationInetrface = new CommonInterface(MainActivity.this, httpListener);
        userInformationInetrface.getInterface("11008", JSON.toJSONString(bean));
    }


    /**
     * 得到应用的版本信息来进行是否升级的判断
     */
    private void getVersionInfo() {
        //获取到当前的版本号
        if (mUpdateManager == null) {
            mUpdateManager = new UpdateManager(this);
        }

        UpdateAppBean bean = new UpdateAppBean();
        bean.setPlat("1");
        CommonInterface updateAppInterface = new CommonInterface(this, httpListener2);
        updateAppInterface.getInterface("15006", JSON.toJSONString(bean));

    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);

            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode != null) {
                if (errCode.equals("0000")) {
                    toast("您已登录！");
                    loginState = true;
                    MyApplication.getApp().setUser(JsonUtil.parseJsonToBean(response, UserInfoBean.class));
                } else {
                    toast("您还没有登录！");
                    loginState = false;
                }
                getVersionInfo();
                SharePreferencesHelper.getInstance(MainActivity.this).putBoolean("loginState", loginState);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            Toast.makeText(MainActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
        }
    };
    HttpListener httpListener2 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            requestBean = JsonUtil.parseJsonToBean(response, UpdateAppRequest.class);
            if (requestBean != null) {
                String versionNo = JsonUtil.getFieldValue(response, "versionNo");
                String version = mUpdateManager.getCurrentVersion(MainActivity.this);
                String downUrl = JsonUtil.getFieldValue(response, "downUrl");
                SharePreferencesHelper.getInstance(MainActivity.this).putString("downUrl", downUrl);

              /*  if (!version.equals(versionNo)) {
                    //需要升级
                    goUpdateApp();
                } else {
                    showCouponPopupWindow();
                }*/
                if (version.compareTo(versionNo) < 0) {
                    //需要升级
                    goUpdateApp();
                } else {
//                    goUpdateApp();
                    showCouponPopupWindow();
                }

            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    /**
     * 分情况进行应用的升级
     */
    private void goUpdateApp() {
        /**
         * 动态获取权限，Android 6.0 新特性，一些保护权限，除了要在AndroidManifest中声明权限，还要使用如下代码动态获取
         */
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        //不强制升级
        mUpdateManager.setUpdateDialog(requestBean);
    }

    /*优惠券弹框*/
    private void showCouponPopupWindow() {
        MessageBean messageBean = new MessageBean();
        messageBean.setUserId(userId);
        messageBean.setToken(token);
        messageBean.setType("1");
        CommonInterface commonInterface = new CommonInterface(MainActivity.this, popupHttpListener);
        commonInterface.getInterface("16024", JSON.toJSONString(messageBean));
    }

    HttpListener popupHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String coverImg = JsonUtil.getFieldValue(response, "coverImg");
                String isView = JsonUtil.getFieldValue(response, "isView");//1、显示  2、不显示
                if (isView.equals("1")) {
                    //当然是先初始化popupWindow
                    popupWindow = new UtilPopupWindow();
                    //我再工具中没有写构造函数，这里调用默认的构造函数
                    WindowManager m = getWindowManager();
                    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                    final int windowHeight = d.getHeight();
                    //弹出框填充布局
                    RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.popupwindow_coupon, null);
                    FrameLayout layout2 = (FrameLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
                    popupWindow.setPopupWindow(MainActivity.this, windowHeight, layout, layout2, Gravity.CENTER);
                    ImageView cover_img = (ImageView) layout.findViewById(R.id.cover_img);
                    if (!cover_img.equals("")) {
                        ImageUtils.loadImageView(MainActivity.this, coverImg, cover_img);
                    } else {
                        ImageUtils.loadImageView(MainActivity.this, R.drawable.symbols_bitmap_home_page, cover_img);
                    }
                    ImageView dimss_pupopwindow = (ImageView) layout.findViewById(R.id.dimss_pupopwindow);
                    cover_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (loginState == false) {
                                Intent loginIntent = new Intent();
                                loginIntent.setClass(MainActivity.this, LoginActivity.class);
                                startActivity(loginIntent);
                            } else {
                                MessageBean messageBean = new MessageBean();
                                messageBean.setUserId(userId);
                                messageBean.setToken(token);
                                messageBean.setType("1");
                                CommonInterface commonInterface = new CommonInterface(MainActivity.this, receiveHttpListener);
                                commonInterface.getInterface("16025", JSON.toJSONString(messageBean));

                            }
                        }
                    });
                    dimss_pupopwindow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
                        }
                    });
                }

            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    /*领取优惠券*/
    HttpListener receiveHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                popupWindow.dismiss();
                Intent intent = new Intent(MainActivity.this, MyCouponsActivity.class);
                startActivity(intent);
            } else {
                ToastUtil.showToast(errMsg);
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("领取失败");
        }
    };

    @Override
    protected void clickEvent(View v) {


    }

    public void onEventMainThread(String message) {
        if (message.equals("1")) {
            showCouponPopupWindow();
        }
    }

    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                toast("再按一次退出应用程序");
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().AppExit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}

